package com.yitao.cms.utils;

import org.apache.log4j.Logger;

import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.parser.ParserDelegator;
import java.io.*;

/**
 * 获取富文本框中的内容
 *
 * @Author: Tqq
 * @Date: 2019/01/11 16:11
 */
public class Html2Text extends HTMLEditorKit.ParserCallback  {
    private static final Logger logger = Logger.getLogger(Html2Text.class);

    private static Html2Text html2Text = new Html2Text();

    StringBuffer s;

    public Html2Text() {
    }

    public void parse(String str) throws IOException {

        InputStream iin = new ByteArrayInputStream(str.getBytes());
        Reader in = new InputStreamReader(iin);
        s = new StringBuffer();
        ParserDelegator delegator = new ParserDelegator();
        delegator.parse(in, this, Boolean.TRUE);
        iin.close();
        in.close();
    }

    public void handleText(char[] text, int pos) {
        s.append(text);
    }

    public String getText() {
        return s.toString();
    }

    public static String getContent(String str) {
        try{
            html2Text.parse(str);
            return html2Text.getText();
        } catch (Exception e) {
            logger.error("获取文本内容", e);
            return "";
        }
    }
}
